﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Collections.Specialized;

namespace SharpWebSocket.Protocol
{
    internal sealed class Draft10HandShakeRequest
    {
        /*
         * 
         * BEGIN Request Sample
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1:2000
Sec-WebSocket-Origin: null
Sec-WebSocket-Key: QcFCojJc289zdVKmV0nk4Q==
Sec-WebSocket-Version: 8
Cookie: CodeSnippetContainerLang=C%23
           END Request Sample
         * 
         */

        internal Draft10HandShakeRequest( Socket newSocket )
        {
            byte[] bytes = new byte[1024];
            int bytelength = newSocket.Receive( bytes );

            string recStr = Encoding.UTF8.GetString( bytes, 0, bytelength );
            Init( recStr );
        }

        internal Draft10HandShakeRequest( string handShakeRecevedString )
        {
            Init( handShakeRecevedString );
        }

        private void Init( string handShakeRecevedString )
        {
            HandShakeRequest = handShakeRecevedString;
            Variables = new NameValueCollection();

            using (System.IO.StringReader sr = new System.IO.StringReader( HandShakeRequest ))
            {
                string line = sr.ReadLine();
                while (line != null)
                {
                    if ( !string.IsNullOrEmpty( line ) && line.Trim() != string.Empty)
                    {
                        string[] splitResult = line.Split( new string[] { ": " }, StringSplitOptions.RemoveEmptyEntries );
                        if (splitResult.Length == 2)
                        {
                            Variables.Add( splitResult[0], splitResult[1] );
                        }
                    }

                    line = sr.ReadLine();
                }
            }
        }

        public string HandShakeRequest
        {
            get;
            set;
        }

        public NameValueCollection Variables
        {
            get;
            set;
        }

        public string Host
        {
            get
            {
                return Variables["Host"];
            }
        }

        public string SecWebSocketKey
        {
            get
            {
                return Variables["Sec-WebSocket-Key"];
            }
        }

        public string SecWebSocketVersion
        {
            get
            {
                return Variables["Sec-WebSocket-Version"];
            }
        }

        public string SecWebSocketOrigin
        {
            get
            {
                return Variables["Sec-WebSocket-Origin"];
            }
        }
    }
}
